<?php

namespace app\api\model\user;

use app\api\model\User;
use app\common\exception\BaseException;
use app\common\model\sharing\Withdraw as WithdrawModel;

/**
 * 分销商提现明细模型
 * Class Withdraw
 * @package app\api\model\dealer
 */
class Withdraw extends WithdrawModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'update_time',
    ];

    /**
     * 获取分销商提现明细
     * @param $user_id
     * @param int $apply_status
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($apply_status, $pay_type, $search)
    {
        $apply_status != -1 && $this->where('apply_status', '=', $apply_status);
        $pay_type > -1 && $this->where('pay_type', '=', $pay_type);
        !empty($search) && $this->where('user.nickName', '=', $search);
        return $this->order(['create_time' => 'desc'])
            ->alias('w')
            ->field('w.*, user.nickName ,user.avatarUrl')
            ->join('user', 'user.user_id = w.user_id', 'LEFT')
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
    }

    /**
     * 获取分销商提现明细
     * @param $user_id
     * @param int $apply_status
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getWxList($user_id, $apply_status)
    {
        $apply_status > -1 && $this->where('apply_status', '=', $apply_status);
        return $this->where("user_id", $user_id)->order(['create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
    }

    /**
     * 提交申请
     * @param User $dealer
     * @param $data
     * @return false|int
     * @throws BaseException
     */
    public function submit($user,$data)
    {
        // 数据验证
        $this->validation($user,$data);
        // 新增申请记录
        $this->save(array_merge($data, [
            'user_id' => $user['user_id'],
            'apply_status' => 10,
            'wxapp_id' => self::$wxapp_id,
        ]));
        // 扣除余额
        (new User())->where("user_id", $user['user_id'])->setDec("balance", $data['money']);
        return true;
    }

    /**
     * 数据验证
     * @param $user
     * @param $data
     * @throws BaseException
     */
    private function validation($user, $data)
    {
        // 最低提现佣金
        if ($data['money'] <= 0) {
            throw new BaseException(['msg' => '提现金额不正确']);
        }
        if ($user['balance'] <= 0) {
            throw new BaseException(['msg' => '当前用户没有可提现佣金']);
        }
        if ($data['money'] > $user['balance']) {
            throw new BaseException(['msg' => '提现金额不能大于可提现佣金']);
        }
        if ($data['money'] < 10) {
            throw new BaseException(['msg' => '最低提现金额为  10']);
        }
    }

}